package by.yakusekmaxim.bookgid.webapp.page.admin.image;

import java.io.File;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.util.lang.Bytes;

import by.yakusekmaxim.bookgid.datamodel.Image;

public class ImageUploadPanel extends Panel {

	private FileUploadField fileUpload;
	private String UPLOAD_FOLDER = "D:\\downloads\\";
	ImageUploadPanel panel;
	private String nameImg;

	public ImageUploadPanel(String id, final Label imageLabel, final Image image) {
		super(id);

		final ImageUploadPanel panel = this;
		Form<Void> formImage = new Form<Void>("formImage") {
			@Override
			protected void onSubmit() {

				final FileUpload uploadedFile = fileUpload.getFileUpload();
				if (uploadedFile != null) {

					// write to a new file
					File newFile = new File(UPLOAD_FOLDER
							+ uploadedFile.getClientFileName());
					nameImg = uploadedFile.getClientFileName();
					// File newFile = new File(UPLOAD_FOLDER
					// + getImageName(uploadedFile, "1"));

					if (newFile.exists()) {
						newFile.delete();
					}

					try {
						newFile.createNewFile();
						uploadedFile.writeTo(newFile);
						info("saved file: " + uploadedFile.getClientFileName());
						
					} catch (Exception e) {
						throw new IllegalStateException("Error");
					}
				}

			}

		};

		// Enable multipart mode (need for uploads file)
		formImage.setMultiPart(true);

		// max upload size, 10k
		formImage.setMaxSize(Bytes.megabytes(10));

		formImage.add(fileUpload = new FileUploadField("fileUpload"));

		formImage.add(new AjaxButton("ajaxSubmit") {
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> formImage) {
				panel.add(AttributeModifier.replace("style", "display: none;"));
				target.add(panel);
				
			}
			
			@Override
			protected void onAfterSubmit(AjaxRequestTarget target, Form<?> formImage) {
				imageLabel.add(AttributeModifier.replace("src",
						"/imagesService/" + nameImg ));
				imageLabel.add(AttributeModifier.replace("style", "display: block;"));
				target.add(imageLabel);
				image.setUrl("/imagesService/" + nameImg);
			}

		});

		formImage.add(new AjaxLink<Void>("ajaxCancel") {
			@Override
			public void onClick(AjaxRequestTarget target) {
				panel.add(AttributeModifier.replace("style", "display: none;"));
				target.add(panel);
			}

		});

		add(formImage);

	}

}
